// import {useState} from "react";

import { useImmer } from "use-immer";

type Artwork = {
	id: number;
	title: string;
	seen: boolean;
};

const initialList :Artwork[] = [
	{id: 0, title: 'Big Bellies', seen: false},
	{id: 1, title: 'Lunar Landscape', seen: false},
	{id: 2, title: 'Terracotta Army', seen: true},
];

const ItemList = ({artworks, onToggle} : {artworks: Artwork[], onToggle: (artworkId : number ,  nextSeen :  boolean) => void}) => {
	return (
		<ul>
			{artworks.map(artwork => (
				<li key={artwork.id}>
					<label>
						<input type="checkbox" checked={artwork.seen} onChange={e => onToggle(artwork.id, e.target.checked)} />
						{artwork.title}
					</label>
				</li>

			))}
		</ul>
	);
}

const BucketList = () => {

	// 如果使用 useState来更新对象数组中的对象值，则需要用map来创建新对象数组，而不是使用find找到对应的索引然后更新对应的数据，因为使用find这会导致指向同一个数据的原始数据改变，从而影响指向该数据的其他数据变更，从而产生未知的错误
	// const [myList, setMyList] = useState(initialList);
	// const [yourList, setYourList] = useState(initialList);
	//
	// const handleToggleMyList = (artworkId : number ,  nextSeen :  boolean) => {
	// 	setMyList(
	// 		myList.map( artwork => artwork.id === artworkId ? {...artwork, seen: nextSeen} : artwork )
	// 	);
	// }
	//
	// const handleToggleYourList = (artworkId : number ,  nextSeen :  boolean) => {
	// 	setYourList(yourList.map(
	// 		artwork => artwork.id === artworkId ? {...artwork, seen: nextSeen} : artwork
	// 	));
	// }

	const [myList, updateMyList] = useImmer(initialList);
	const [yourList, updateYourList] = useImmer(initialList);
	const handleToggleMyList = (artworkId : number ,  nextSeen :  boolean) => {
		updateMyList(draft => {
			const artwork = draft.find(a => a.id === artworkId);
			if (artwork) {
				artwork.seen = nextSeen;
			}
		});
	}
	const handleToggleYourList = (artworkId : number ,  nextSeen :  boolean) => {
		updateYourList(draft => {
			const artwork = draft.find(a => a.id === artworkId);
			if (artwork) {
				artwork.seen = nextSeen;
			}
		});
	}

	return (
		<>
			<section>
				<h2>My list of art to see</h2>
				<ItemList artworks={myList} onToggle={handleToggleMyList} />
			</section>
			<section>
				<h2>Your list of art to see</h2>
				<ItemList artworks={yourList} onToggle={handleToggleYourList} />
			</section>
		</>
	);
}

export default BucketList;